import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Space, Button, Pagination, message, Modal, Tooltip, Card } from 'antd';
import DraggableTable from '@/components/DraggableTable';
import DataTableActions from './DataTableActions';
import request from '@/utils/request';
import { useNavigate } from 'react-router-dom';
import TopActionBar from '../DataManagement/TopActionBar';
import { restoreColumns, saveColumns, getSortState } from '@/utils/columnStorage';

// OtherDataPanel 组件
// 用于承载其他数据的搜索、列表、操作等右侧内容
// 后续将从DataManagement页面迁移相关逻辑和UI到此组件

// 其他数据面板，负责右侧所有业务逻辑
const OtherDataPanel = ({ otherDataKey, visible }) => {
  const navigate = useNavigate();
  // 关键字搜索
  const [searchKeyword, setSearchKeyword] = useState('');
  // 分页
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  // 表格数据
  const [tableData, setTableData] = useState([]);
  // loading
  const [tableLoading, setTableLoading] = useState(false);
  // 选中行
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // 滚动高度
  const [tableScrollY, setTableScrollY] = useState(0);
  // data level信息
  const [dataLevel, setDataLevel] = useState({ level: 'all', count: 0, size: 0 });
  // 排序状态
  const [sortState, setSortState] = useState({ field: null, order: null });
  const tableContainerRef = useRef(null);
  // TopActionBar ref
  const topActionBarRef = useRef(null);
  // 列
  const defaultColumns = [
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name',
      width: 180,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '文件路径',
      dataIndex: 'file_path',
      key: 'file_path',
      width: 180,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '文件大小',
      dataIndex: 'data_size',
      key: 'data_size',
      width: 80,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '归档时间',
      dataIndex: 'archive_time',
      key: 'archive_time',
      width: 180,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '状态',
      dataIndex: 'bk_pstate',
      key: 'bk_pstate',
      width: 80,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    }
  ];
  
  // 表格列
  const [columns, setColumns] = useState<any[]>([]);

  // 监听表格容器高度变化，动态设置滚动高度
  const calculateTableScrollHeight = () => {
    if (visible && tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 42;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  useEffect(() => {
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  useEffect(() => {
    calculateTableScrollHeight();
  }, [visible]);

  // 监听数据key变化，重置分页和关键字
  useEffect(() => {
    // 恢复排序状态
    const tableKey = 'data_search_other_table';
    const savedSortState = getSortState(tableKey);
    if (savedSortState) {
      setSortState(savedSortState);
    }
    
    setCurrent(1);
    setSearchKeyword('');
    setSelectedRowKeys([]);
  }, [otherDataKey]);

  // 保存列配置到localStorage
  useEffect(() => {
    if (columns.length > 0) {
      const tableKey = 'data_search_other_table';
      saveColumns(columns, tableKey, sortState);
    }
  }, [columns, sortState]);

  // 拉取数据和动态列
  const fetchData = async (curPage = current, size = pageSize, search = searchKeyword) => {
    if (!otherDataKey) return;
    setTableLoading(true);
    try {
      const res = await request.get('/Management/AdvancedDataList', {
        params: {
          file_name: search,
          advanced_data_id: 1,
          data_key: otherDataKey,
          page_size: size,
          page: curPage
        }
      });
      if (res.status === 200 && res.data.data) {
        const { columns: colArr = [], list = [], count = 0, data_level } = res.data.data;
        // 更新data_level信息
        if (data_level) {
          setDataLevel(data_level);
        }
        // 合并默认字段和后端字段，默认字段优先，去重
        const allColArr = [
          ...defaultColumns.map(col => col.dataIndex),
          ...colArr.filter(col => !defaultColumns.some(def => def.dataIndex === col))
        ];
        // 动态生成columns
        const dynamicColumns = allColArr.map((col) => {
          const defaultCol = defaultColumns.find(def => def.dataIndex === col);
          if (defaultCol) return defaultCol;
          return {
            title: col,
            dataIndex: col,
            key: col,
            width: 100,
            ellipsis: { showTitle: false },
            render: (text) => (
              <Tooltip title={text}>
                <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
              </Tooltip>
            )
          };
        });
        // 固定操作列
        dynamicColumns.push({
          title: '操作',
          key: 'action',
          width: 100,
          fixed: 'right',
          align: 'center' as const,
          render: (_, record) => (
            <Space>
              <Button size="small" onClick={() => handleDownload(record)}>
                下载
              </Button>
              {record.is_favorites ? (
                <Button 
                  size="small" 
                  icon={<span style={{ color: '#ffd700' }}>★</span>} 
                  onClick={() => handleUnfavorite(record)}
                >
                  收藏
                </Button>
              ) : (
                <Button size="small" icon={<span>★</span>} onClick={() => handleFavorite(record)}>
                  收藏
                </Button>
              )}
            </Space>
          )
        });
        // 从localStorage恢复列配置
        const tableKey = 'data_search_other_table';
        const restoredColumns = restoreColumns(dynamicColumns, tableKey);
        setColumns(restoredColumns);
        
        // 恢复排序状态
        const savedSortState = getSortState(tableKey);
        if (savedSortState) {
          setSortState(savedSortState);
        }
        // 数据加key
        const tableData = list.map((item, idx) => ({
          ...item,
          key: item.product_id ? item.product_id : `${otherDataKey}_${idx}`
        }));
        setTableData(tableData);
        setTotal(count);
      }
    } catch (e) {
      message.error(e?.message || '获取数据失败');
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    fetchData(current, pageSize, searchKeyword);
    // eslint-disable-next-line
  }, [otherDataKey, current, pageSize]);

  // 下载
  const handleDownload = (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法下载');
      return;
    }
    const url = request.getUrl(`/Management/Download?data_type=${record.data_type}&product_id=${record.product_id}`);
    window.open(url, '_blank');
  };

  // 删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件"${record.file_name || record['文件名']}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: [
              {
                data_type: record.data_type,
                product_id: record.product_id
              }
            ]
          };
          const res = await request.post('/Management/DataDelete', payload);
          if (res.status === 200) {
            message.success('删除成功');
            fetchData(current, pageSize, searchKeyword);
          }
        } catch (e) {
          message.error(e?.message || '删除失败');
        }
      }
    });
  };

  // 收藏
  const handleFavorite = async (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法收藏');
      return;
    }
    try {
      const payload = {
        files: [
          {
            data_type: record.data_type,
            product_id: record.product_id
          }
        ]
      };
      const res = await request.post('/Management/Favorites', payload);
      if (res.status === 200) {
        message.success('收藏成功');
        setTableData((prevData) => prevData.map((item) => (item.key === record.key ? { ...item, is_favorites: 1 } : item)));
      }
    } catch (e) {
      message.error(e?.message || '收藏失败');
    }
  };

  // 取消收藏
  const handleUnfavorite = async (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法取消收藏');
      return;
    }
    try {
      const res = await request.post('/Management/FavoritesCancel', {
        file_ids: [record.key]
      });
      if (res.status === 200) {
        message.success('取消收藏成功');
        setTableData((prevData) => prevData.map((item) => (item.key === record.key ? { ...item, is_favorites: 0 } : item)));
      }
    } catch (e) {
      message.error(e?.message || '取消收藏失败');
    }
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys) => {
      setSelectedRowKeys(keys);
    }
  };

  // 处理分页变化
  const handlePageChange = (page, size) => {
    setCurrent(page);
    setPageSize(size);
  };

  // 处理搜索
  const handleSearch = () => {
    setCurrent(1);
    fetchData(1, pageSize, searchKeyword);
  };

  // 处理清除
  const handleClear = () => {
    setSearchKeyword('');
    setCurrent(1);
    setTimeout(() => {
      fetchData(1, pageSize, '');
    }, 0);
  };

  // 格式化文件大小
  const formatFileSize = (size) => {
    if (size < 1024) {
      return size + ' B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + ' KB';
    } else if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(2) + ' MB';
    } else {
      return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    }
  };

  return (
    <div
      className="data-management-right"
      style={{ ...{ flex: '1', overflow: 'auto', minWidth: 0 }, display: visible ? 'flex' : 'none' }}
    >
      {/* 顶部搜索区 */}
      <Form layout="inline" className="filter-form">
        <Form.Item style={{ width: 320 }} label="关键字">
          <Input
            placeholder="请输入关键字进行检索"
            value={searchKeyword}
            onChange={e => setSearchKeyword(e.target.value)}
            style={{ width: '100%' }}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>
              筛选
            </Button>
            <Button onClick={handleClear}>清除</Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 固定项筛选条 */}
      <div className="fixed-filter-tabs">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
          <div
            style={{
              overflowX: 'auto',
              whiteSpace: 'nowrap',
              overflowY: 'hidden',
              marginRight: 10,
              lineHeight: '22px'
            }}
          >
            <span className="filter-tab-item active">
              {dataLevel.level === 'all' ? '全部' : dataLevel.level}({dataLevel.count}/{formatFileSize(dataLevel.size)})
            </span>
          </div>
          <div>
            <TopActionBar ref={topActionBarRef} showReleaseHistory={false} />
          </div>
        </div>
      </div>

      {/* 数据表格 */}
      <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
        <DraggableTable
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          pagination={false}
          tableLayout="fixed"
          style={{ flex: 1 }}
          scroll={{ y: tableScrollY, x: 'max-content' }}
          bordered
          size="small"
          loading={tableLoading}
          rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          onChange={(pagination, filters, sorter) => {
            if (sorter.field) {
              const newSortState = {
                field: sorter.field,
                order: sorter.order
              };
              setSortState(newSortState);
            }
          }}
          onColumnsChange={(columns) => {
            setColumns(columns);
          }}
        />
      </div>
      {/* 表格下方操作按钮和分页 */}
      <div
        className="table-footer-bar"
        style={{ marginTop: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="action-buttons" style={{ marginBottom: 0, boxShadow: 'none', borderRadius: 0, background: 'none', padding: 0 }}>
          <DataTableActions
		  	advanced={true}
            selectedRowKeys={selectedRowKeys}
            setSelectedRowKeys={setSelectedRowKeys}
            dataKey={otherDataKey}
            tableData={tableData}
            filterParams={{}}
            fetchTableData={() => fetchData(current, pageSize, searchKeyword)}
            refreshDownloadingCount={() => {
              try { (topActionBarRef.current as any)?.refreshDownloadingCount?.(); } catch(e) {}
            }}
          />
        </div>
        <Pagination
          current={current}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          style={{ marginTop: 0 }}
          pageSizeOptions={['10', '20', '50']}
          onChange={handlePageChange}
          showTotal={total => `共 ${total} 条`}
        />
      </div>
    </div>
  );
};

export default OtherDataPanel; 